//
//  BadgeView.swift
//  Social
//
//  Created by 李响 on 2019/3/19.
//  Copyright © 2019 shengsheng. All rights reserved.
//

import UIKit

class BadgeView: UIView {
    
    private lazy var label: UILabel = {
        $0.backgroundColor = .red
        $0.textColor = .white
        $0.textAlignment = .center
        $0.font = .systemFont(ofSize: 10)
        $0.layer.masksToBounds = true
        return $0
    } ( UILabel() )
    
    /// 位置偏移
    var offset: CGPoint = .zero {
        didSet { layoutSubviews() }
    }
    
    /// 边距 默认为字号大小的0.4倍
    var margin: CGFloat = 0.4 {
        didSet { layoutSubviews() }
    }
    
    /// 颜色 默认为红色
    var color: UIColor = .red {
        didSet { label.backgroundColor = color }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setup()
        setupLayout()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setup()
        setupLayout()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        setupLayout()
    }
    
    private func setup() {
        isUserInteractionEnabled = false
        addSubview(label)
    }
    
    private func setupLayout() {
        let height = label.font.pointSize * (1.0 + margin)
        let size = label.sizeThatFits(CGSize(width: bounds.width, height: height))
        let width = max(size.width + height * margin, height)
        let rect = CGRect(
            x: bounds.width - width + offset.x,
            y: 0 + offset.y,
            width: width,
            height: height
        )
        
        label.frame = rect
        label.layer.cornerRadius = height * 0.5
    }
}

extension BadgeView {
    
    func set(text: String) {
        label.text = text
        layoutSubviews()
    }
    
    func set(font: UIFont) {
        label.font = font
        layoutSubviews()
    }
}
